using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ECommerce.Library;
using AutoGear.BLL;
using System.IO;
using eShop.Model;

/// <summary>
/// Summary description for BrandFileAccessUtility
/// </summary>

namespace AutoGear.BLL
{
    public sealed class BrandFileAccessUtility : FileAccessUtility
    {
        private const string _brandRootPath = "~/manufacturer/";
        //private const string _brandTemplateFilePath = "~/templates/brand-template.txt";
        //private const string _brandTemplateCsFilePath = "~/templates/brand-template-cs.txt";

        private BrandFileAccessUtility() { }

        public static Manufacturer CreateBrandFiles(Manufacturer newBrand, string temporaryLogoPath, string temporaryCatalogPath)
        {
            if (newBrand == null)
                throw new ArgumentNullException("newBrand in BrandFileAccessUtility.CreateBrandFiles");
            if (string.IsNullOrEmpty(newBrand.BrandName))
                throw new ArgumentNullException("newBrand.BrandName in BrandFileAccessUtility.CreateBrandFiles");
            //if (string.IsNullOrEmpty(_brandTemplateFilePath))
            //    throw new ArgumentNullException("_brandTemplateFilePath in BrandFileAccessUtility.CreateBrandFiles");
            if (string.IsNullOrEmpty(_brandRootPath))
                throw new ArgumentNullException("_brandRootPath in BrandFileAccessUtility.CreateBrandFiles");

            string cleanBrandName = SiteUtility.CleanBrandName(newBrand.BrandName);
            string newBrandPath = _brandRootPath + cleanBrandName + ".aspx";
            newBrandPath = newBrandPath.ToLower();

            if (File.Exists(HttpContext.Current.Server.MapPath(newBrandPath)))
                DeleteBrandFiles(newBrand);

            //if (File.Exists(HttpContext.Current.Server.MapPath(_brandTemplateFilePath)))
            //{
            //    try
            //    {
            //        TextReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_brandTemplateFilePath));
            //        string templateContent = reader.ReadToEnd();
            //        reader.Close();

            //        templateContent = templateContent.Replace("<##PageName##>", cleanBrandName);
            //        templateContent = templateContent.Replace("<##PageClassName##>", cleanBrandName.Replace('-', '_').ToLower());
            //        templateContent = templateContent.Replace("<##BrandId##>", newBrand.ProductBrandId.ToString());

            //        if (!CreateFile(newBrandPath, templateContent))
            //            throw new IOException("Failed to create files for brand in BrandFileAccessUtility.CreateBrandFiles");
            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //}
            //else
            //    throw new IOException("_brandTemplateFilePath in BrandFileAccessUtility.CreateBrandFiles");


            //if (File.Exists(HttpContext.Current.Server.MapPath(_brandTemplateCsFilePath)))
            //{
            //    try
            //    {
            //        TextReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_brandTemplateCsFilePath));
            //        string templateContent = reader.ReadToEnd();
            //        reader.Close();

            //        templateContent = templateContent.Replace("<##PageClassName##>", cleanBrandName.Replace('-', '_').ToLower());

            //        if (!CreateFile(newBrandPath + ".cs", templateContent))
            //            throw new IOException("Failed to create files for brand in BrandFileAccessUtility.CreateBrandFiles");
            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //}
            //else
            //    throw new IOException("_brandTemplateCsFilePath in BrandFileAccessUtility.CreateBrandFiles");

            string brandDefaultImageUrl = string.Empty;
            if (brandDefaultImageUrl != string.Empty)
            {
                try
                {
                    FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryLogoPath));
                    if (logoInfo.Exists)
                    {
                        string logoFileName = cleanBrandName.ToLower() + logoInfo.Extension;
                        logoFileName = ImageResizer.RandomizeImageFileName(logoFileName);
                        brandDefaultImageUrl = UploadBrandLogo(temporaryLogoPath, logoFileName, true);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            string brandCatalogFileUrl = string.Empty;
            if (brandCatalogFileUrl != string.Empty)
            {
                try
                {
                    FileInfo catalogInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryCatalogPath));
                    if (catalogInfo.Exists)
                    {
                        string catalogFileName = catalogInfo.Name.Insert(catalogInfo.Name.LastIndexOf('.'),
                            "_" + newBrand.ProductBrandId.ToString());
                        brandCatalogFileUrl = UploadCatalogFile(temporaryCatalogPath, catalogFileName);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return newBrand;
        }

        public static bool DeleteBrandFiles(Manufacturer oldBrand)
        {
            if (oldBrand == null)
                throw new ArgumentNullException("oldBrand in BrandFileAccessUtility.DeleteBrandFiles");
            if (string.IsNullOrEmpty(oldBrand.BrandName))
                throw new ArgumentNullException("oldBrand.BrandName in BrandFileAccessUtility.DeleteBrandFiles");
            //if (string.IsNullOrEmpty(_brandTemplateFilePath))
            //    throw new ArgumentNullException("_brandTemplateFilePath in BrandFileAccessUtility.DeleteBrandFiles");
            if (string.IsNullOrEmpty(_brandRootPath))
                throw new ArgumentNullException("_brandRootPath in BrandFileAccessUtility.DeleteBrandFiles");

            string cleanBrandName = SiteUtility.CleanBrandName(oldBrand.BrandName);
            string oldBrandPath = _brandRootPath + cleanBrandName + ".aspx";
            oldBrandPath = oldBrandPath.ToLower();

            string pathToDelete = HttpContext.Current.Server.MapPath(oldBrandPath).ToLower();
            string siteRootPath = HttpContext.Current.Server.MapPath("~").ToLower();

            if (pathToDelete.StartsWith(siteRootPath) && pathToDelete.Length <= siteRootPath.Length + 1)
                throw new InvalidOperationException("Delete Path is not valid in BrandFileAccessUtility.DeleteBrandFiles");

            bool result = true;

            if (File.Exists(HttpContext.Current.Server.MapPath(oldBrandPath)))
            {
                try
                {
                    result &= DeleteFile(oldBrandPath);
                }
                catch (Exception ex)
                {
                    throw new IOException("Failed to delete aspx file in BrandFileAccessUtility.DeleteBrandFiles");
                }
            }

            if (File.Exists(HttpContext.Current.Server.MapPath(oldBrandPath + ".cs")))
            {
                try
                {
                    result &= DeleteFile(oldBrandPath + ".cs");
                }
                catch (Exception ex)
                {
                    throw new IOException("Failed to delete cs file in BrandFileAccessUtility.DeleteBrandFiles");
                }
            }

            return result;
        }

        public static string UpdateBrandLogo(string temporaryLogoPath, string outputFileName)
        {
            if (string.IsNullOrEmpty(temporaryLogoPath))
                throw new ArgumentNullException("temporaryLogoPath in BrandFileAccessUtility.UploadBrandLogo()");
            if (string.IsNullOrEmpty(outputFileName))
                throw new ArgumentNullException("outputFileName in BrandFileAccessUtility.UploadBrandLogo()");

            string brandDefaultImageUrl = null;
            try
            {
                FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryLogoPath));
                if (logoInfo.Exists)
                {
                    FileInfo newLogoInfo = new FileInfo(outputFileName);

                    brandDefaultImageUrl = UploadBrandLogo(temporaryLogoPath, ImageResizer.RandomizeImageFileName(newLogoInfo.Name), false);
                }
                return brandDefaultImageUrl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string UploadBrandLogo(string temporaryImagePath, string imageName, bool addSufix)
        {
            try
            {
                const int maxImageWidth = 146;
                const string brandImageRootPath = "~/upload/images/brand/";

                string outputFilePath = brandImageRootPath + imageName;

                System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(temporaryImagePath);

                string bigImagePath = null;

                if(addSufix)
                    ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_max");
                else
                    ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath.Replace("big","max"), originalImageDimension.Width, false, string.Empty);

                if (originalImageDimension.Width > maxImageWidth)
                {
                    if(addSufix)
                        bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, maxImageWidth, true, "_big");
                    else
                        bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, maxImageWidth, false, string.Empty);
                }
                else
                {
                    if(addSufix)
                        bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_big");
                    else
                        bigImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, false, string.Empty);
                }
                FileAccessUtility.DeleteFile(temporaryImagePath);

                return bigImagePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string UploadCatalogFile(string temporaryCatalogPath, string fileName)
        {
            try
            {
                const string catalogRootPath = "~/upload/brand_catalog/";

                string catalogPath = catalogRootPath + fileName;

                if (File.Exists(HttpContext.Current.Server.MapPath(catalogPath)))
                    FileAccessUtility.DeleteFile(catalogPath);

                File.Copy(HttpContext.Current.Server.MapPath(temporaryCatalogPath), 
                    HttpContext.Current.Server.MapPath(catalogPath));

                FileAccessUtility.DeleteFile(temporaryCatalogPath);

                return catalogPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool DeleteBrandLogo(Manufacturer brand)
        {
            FileAccessUtility.DeleteFile(brand.BrandImageUrl);
            FileAccessUtility.DeleteFile(brand.BrandImageUrl.Replace("big","max"));
            return true;
        }

      
        public static string UpdateBrandCatalog(string temporaryCatalogPath, string catalogFileName)
        {
            try
            {
                const string catalogRootPath = "~/upload/brand_catalog/";

                string catalogPath = catalogRootPath + catalogFileName;

                if (File.Exists(HttpContext.Current.Server.MapPath(catalogPath)))
                    FileAccessUtility.DeleteFile(catalogPath);

                File.Copy(HttpContext.Current.Server.MapPath(temporaryCatalogPath),
                    HttpContext.Current.Server.MapPath(catalogPath));

                FileAccessUtility.DeleteFile(temporaryCatalogPath);

                return catalogPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}